<?php

namespace app\admin\controller\bushen;

use app\admin\controller\buchang\Exception;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
use think\response\Json;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Hejia extends Backend
{
    protected $noNeedLogin = ['*'];
    /**
     * Baoan模型对象
     * @var \app\admin\model\buchang\Baoan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\buchang\Baoan;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->site = Config::get('site');
        $this->view->assign('chexing', $this->site['chexing']);
        $this->view->assign('xingzhi', $this->site['xingzhi']);
        $this->view->assign('task', $this->site['task_list']);
        $this->view->assign('site', $this->site);
    }

    public function export_excel()
    {
        $id   = input('id');
        $type = input('type');
        if (empty($id) || empty($type)) {
            exit();
        }
        $path = dirname(__FILE__); //找到当前脚本所在路径
        vendor("PHPExcel.PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.Writer.IWriter");
        vendor("PHPExcel.PHPExcel.Writer.Abstract");
        vendor("PHPExcel.PHPExcel.Writer.Excel5");
        vendor("PHPExcel.PHPExcel.Writer.Excel2007");
        vendor("PHPExcel.PHPExcel.IOFactory");
        $objPHPExcel = new \PHPExcel();
        $objWriter   = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter   = new \PHPExcel_Writer_Excel2007($objPHPExcel);

        if ($type == 1) {
            $filename = "本车配件";
            $list     = Db::name('peijian')->where('bid', $id)->select();
            // 设置表头信息
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '序号')
                ->setCellValue('B1', '配件名称')
                ->setCellValue('C1', '价格方案')
                ->setCellValue('D1', '价格')
                ->setCellValue('E1', '数量')
                ->setCellValue('F1', '金额')
                ->setCellValue('G1', '核定价格')
                ->setCellValue('H1', '核定数量')
                ->setCellValue('I1', '核价金额');
            $i     = 2;             //定义一个i变量，目的是在循环输出数据是控制行数
            $count = count($list);  //计算有多少条数据

            for ($i = 2; $i <= $count + 1; $i++) {
                $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $list[$i - 2]['xuhao']);
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $list[$i - 2]['name']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $list[$i - 2]['fangan']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $list[$i - 2]['price']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $list[$i - 2]['num']);
                $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $list[$i - 2]['money']);
                $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $list[$i - 2]['price_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $list[$i - 2]['num_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $list[$i - 2]['hejia']);
            }
        } elseif ($type == 2) {
            $filename = "本车工时";
            $list     = Db::name('bengong')->where('bid', $id)->select();
            // 设置表头信息
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '序号')
                ->setCellValue('B1', '配件名称')
                ->setCellValue('C1', '价格方案')
                ->setCellValue('D1', '价格')
                ->setCellValue('E1', '数量')
                ->setCellValue('F1', '金额')
                ->setCellValue('G1', '核定价格')
                ->setCellValue('H1', '核定数量')
                ->setCellValue('I1', '核价金额');
            $i     = 2;             //定义一个i变量，目的是在循环输出数据是控制行数
            $count = count($list);  //计算有多少条数据

            for ($i = 2; $i <= $count + 1; $i++) {
                $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $list[$i - 2]['xuhao']);
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $list[$i - 2]['name']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $list[$i - 2]['fangan']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $list[$i - 2]['price']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $list[$i - 2]['num']);
                $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $list[$i - 2]['money']);
                $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $list[$i - 2]['price_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $list[$i - 2]['num_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $list[$i - 2]['hejia']);
            }
        } elseif ($type == 3) {
            $filename = "三者车配件";
            $list     = Db::name('sanpei')->where('sid', $id)->select();
            // 设置表头信息
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '序号')
                ->setCellValue('B1', '配件名称')
                ->setCellValue('C1', '价格方案')
                ->setCellValue('D1', '价格')
                ->setCellValue('E1', '数量')
                ->setCellValue('F1', '金额')
                ->setCellValue('G1', '核定价格')
                ->setCellValue('H1', '核定数量')
                ->setCellValue('I1', '核价金额');
            $i     = 2;             //定义一个i变量，目的是在循环输出数据是控制行数
            $count = count($list);  //计算有多少条数据

            for ($i = 2; $i <= $count + 1; $i++) {
                $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $list[$i - 2]['xuhao']);
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $list[$i - 2]['name']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $list[$i - 2]['fangan']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $list[$i - 2]['price']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $list[$i - 2]['num']);
                $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $list[$i - 2]['money']);
                $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $list[$i - 2]['price_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $list[$i - 2]['num_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $list[$i - 2]['hejia']);
            }
        } elseif ($type == 4) {
            $filename = "三者车工时";
            $list     = Db::name('sangong')->where('sid', $id)->select();
            // 设置表头信息
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '序号')
                ->setCellValue('B1', '配件名称')
                ->setCellValue('C1', '价格方案')
                ->setCellValue('D1', '价格')
                ->setCellValue('E1', '数量')
                ->setCellValue('F1', '金额')
                ->setCellValue('G1', '核定价格')
                ->setCellValue('H1', '核定数量')
                ->setCellValue('I1', '核价金额');
            $i     = 2;             //定义一个i变量，目的是在循环输出数据是控制行数
            $count = count($list);  //计算有多少条数据

            for ($i = 2; $i <= $count + 1; $i++) {
                $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $list[$i - 2]['xuhao']);
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $list[$i - 2]['name']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $list[$i - 2]['fangan']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $list[$i - 2]['price']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $list[$i - 2]['num']);
                $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $list[$i - 2]['money']);
                $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $list[$i - 2]['price_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $list[$i - 2]['num_he']);
                $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $list[$i - 2]['hejia']);
            }
        } else {
            $filename = "未定义类型";
        }

        /*--------------下面是设置其他信息------------------*/
        $objPHPExcel->getActiveSheet()->setTitle('sheet1');                       //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                                     //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来

        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
        ob_end_clean();
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
        exit();
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $customWhere = [];
        $filterInfo  = $this->request->get('filter', '');
        $filterInfo  = (array)json_decode($filterInfo, true);
        $type        = 1;
        if (isset($filterInfo['type'])) {
            // 移除where条件中关于status的信息
            $op   = json_decode($this->request->get("op"), true);
            $type = $filterInfo['type'];
            unset($filterInfo['type'], $op['type']);

            // 前端请求参数重新赋值，使得在接下来的where条件中没有status
            $this->request->get(['filter' => json_encode($filterInfo), 'op' => json_encode($op)]);
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $wheres = '1=1';
        switch ($type) {
            case 1:
                // 本车定损
                $table  = "baoan";
                $wheres .= " and baoan.status = 1";
                $list   = Db::name("baoan")
                    ->alias('baoan')
                    ->where($where)
                    ->where($wheres)
                    ->order($sort, $order)
//            ->select(false);
                    ->paginate($limit);

                break;
            case 2:
                // 三者车损（新）
                $table  = "sanche";
                $wheres .= " and other.status = 1";
                break;
            case 3:
                // 三者财物损失（新）
                $table  = "scwusun";
                $wheres .= " and other.status = 1";
                break;
            case 4:
                // 本车人伤
                $table  = "benren";
                $wheres .= " and other.status = 1";
                break;
            case 5:
                // 三者人伤
                $table  = "sanren";
                $wheres .= " and other.status = 1";
                break;
            default:
                // 条件不匹配任何值时执行的代码
        }
        if ($type <> 1) {
            $list = Db::name($table)
                ->alias('other')
                ->join('baoan baoan', 'other.bid = baoan.id', 'left')
                ->where($where)
                ->where($wheres)
                ->field('other.id,baoan.baoan_id,baoan.baoan_time,baoan.chuxian_time,baoan.phone,baoan.tong_number,baoan.car_num,baoan.car_vin,baoan.learned_name,baoan.yw_hetong_time,baoan.plan_endtime,baoan.chakan_ren,baoan.buchang_money,other.status,baoan.gs_type')
                ->order($sort, $order)
//            ->select(false);
                ->paginate($limit);
        }
        $admin = $this->auth->getUserInfo();
        foreach ($list as $k => &$v) {
            $v['type'] = $type;
            $list[$k]  = $v;
        }

        $data['chesun_num_1'] = Db::name('baoan')->where('status', '1')->count();
        $data['chesun_num_2'] = Db::name('sanche')->alias('a')->join('baoan b', 'a.bid = b.id')->where('a.status', '1')->count();
        $data['chesun_num_3'] = Db::name('scwusun')->alias('a')->join('baoan b', 'a.bid = b.id')->where('a.status', '1')->count();
        $data['chesun_num_4'] = Db::name('benren')->alias('a')->join('baoan b', 'a.bid = b.id')->where('a.status', '1')->count();
        $data['chesun_num_5'] = Db::name('sanren')->alias('a')->join('baoan b', 'a.bid = b.id')->where('a.status', '1')->count();


        $result = ['total' => $list->total(), 'rows' => $list->items(), 'data' => $data];
        return json($result);
    }

    /**
     * 审核
     * @param $type
     * @param $id
     * @return mixed
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function shenhe($type = null, $id = null)
    {
        $this->assign('orderid', $id);
        $hd_num   = 0;
        $hd_money = 0;
        $hd_sum   = 0;
        $ids      = $id;
        if ($type == 1) {
            $id = $id;
        } elseif ($type == 2) {
            $id     = Db::name("sanche")->where("id", $ids)->value("bid");
            $sanche = Db::name('sanche')->where('id', $ids)->select();

            $this->assign('sanche', $sanche);
            $hd_num   = 0;
            $hd_money = 0;
            $hd_sum   = 0;
        } elseif ($type == 3) {
            $id      = Db::name("scwusun")->where("id", $ids)->value("bid");
            $scwusun = Db::name('scwusun')->where('id', $ids)->select();

            foreach ($scwusun as $key => &$value) {
                $value['dong_hd_num']   = Db::name("sancai")->where("sid", $value['id'])->sum("num_he");
                $value['dong_hd_money'] = Db::name("sancai")->where("sid", $value['id'])->sum("price_he");
                $value['dong_hd_sum']   = Db::name("sancai")->where("sid", $value['id'])->sum("hejia");
                $sancai                 = Db::name('sancai')->where('sid', $value['id'])->field('sum(hejia) as he_ding,sum(money) as jin_e')->find();
                $value['he_ding']       = $sancai['he_ding'];
                $value['jin_e']         = $sancai['jin_e'];
            }
            $this->assign('scwusun', $scwusun);

            $hd_num   = Db::name("sancai")->where("sid", $ids)->sum("num_he");
            $hd_money = Db::name("sancai")->where("sid", $ids)->sum("price_he");
            $hd_sum   = Db::name("sancai")->where("sid", $ids)->sum("hejia");
        } elseif ($type == 4) {
            $id     = Db::name("benren")->where("id", $ids)->value("bid");
            $benren = Db::name('benren')->where('id', $ids)->select();
            $this->assign('benren', $benren);

            $hd_sum = Db::name("renshang")->where("bid", $ids)->sum("hejia");
        } elseif ($type == 5) {
            $id     = Db::name("sanren")->where("id", $ids)->value("bid");
            $sanren = Db::name('sanren')->where('id', $ids)->select();
//            dump($sanren);die;
            $this->assign('sanren', $sanren);

            $hd_sum = Db::name("renshang")->where("sid", $ids)->sum("hejia");
        }
        //查询服务单
        $baoan                      = Db::name('baoan')->where(['id' => $id])->find();
        $baoan['yw_class_text']     = Db::name('zuzhi')->where('id', $baoan['yw_class'])->value('name');
        $baoan['chakan_group_name'] = Db::name('zuzhi')->where('id', $baoan['chakan_group'])->value('name');

        $list_one                  = Db::name('list_one')->where(['tong_number' => $baoan['tong_number']])->find();
        $list_one['yw_class_text'] = $baoan['yw_class_text'];
        $this->assign('row', $baoan);
        $this->assign('res', $list_one);

        //图片
        $file = Db::name('files')->where('bid', $id)->column('url');
        $this->assign('files', implode(',', $file));

        $this->assign('hd_num', $hd_num);
        $this->assign('hd_money', $hd_money);
        $this->assign('hd_sum', $hd_sum);

        $peijian  = Db::name('peijian')->where('bid', $id)->select();
//        dump($peijian);die;
        $peijian1 = 1;
        foreach ($peijian as $k => $v) {
            if ($v['num_he'] <> 0) {
                $peijian1 = 2;
            }
        }

        $this->assign('peijian1', $peijian1);
        $this->assign('peijian', $peijian);
        $bengong = Db::name('bengong')->where('bid', $id)->select();

        $bengong1 = 1;
        foreach ($bengong as $k => $v) {
            if ($v['num_he'] <> 0) {
                $bengong1 = 2;
            }
        }
        $this->assign('bengong1', $bengong1);
        $this->assign('bengong', $bengong);
        $bencai = Db::name('bencai')->where('bid', $id)->select();
        $this->assign('bencai', $bencai);
        $lisuan = Db::name('lisuan')->where('bid', $id)->where("type", $type)->find();
        $this->assign('lisuan', $lisuan);
        $shoukuan = Db::name('shoukuan')->where('bid', $id)->select();
        $this->assign('shoukuan', $shoukuan);

        $qita = Db::name('qita')->where('bid', $id)->select();
        $this->assign('qita', $qita);

        $yijian = Db::name('byijian')->where('bid', $id)->where("type", $type)->select();
        $this->assign('yijian', $yijian);

        $this->assign('selectMenu', Loader::model('Zuzhi')->selectMenu());
        $this->assign('type', $type);
        $this->assign('bid', $baoan['id']);

//        dump($baoan);die;
        return $this->fetch();
    }


    /**
     * 审核通过
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function shenhe_post()
    {
        $data = request()->param();
//        dump($data);die;
        $id              = $data['id'];
        $bid             = $data['bid'];
        $date['up_time'] = time();
        $tuihui          = $data['tuihui'];
        if ($tuihui) {
            $tuihui = ":" . $tuihui;
        }
        $type = 0;
        // 启动事务
        Db::startTrans();
        try {
            if (!empty($data['chesun_1'])) {
                $type = 1;
                // $date['chesun_1']=$data['chesun_1'];
                if ($data['chesun_1'] == 3) {
                    $msg            = '本车定损核价审核通过';
                    $date['status'] = 2;
                    $date['tui']    = 1;
                    Db::name('lisuan')->where('bid', $bid)->where("sid", $id)->where('type',1)->delete();
                }
                if ($data['chesun_1'] == 2) {
                    $msg            = '本车定损核价退回';
                    $date['status'] = 0;
                    $date['tui']    = 2;
                }
                $res = Db::name('baoan')->where('id', $id)->where("status", "1")->update($date);
            } elseif (!empty($data['chesun_2'])) {
                // $date['chesun_2']=$data['chesun_2'];
                // if($date['chesun_2']==3){
                //     $msg = '本车财物定损审核通过';
                // }
                // if($date['chesun_2']==2){
                //     $msg = '本车财物定损返回';
                // }
                exit();
            } elseif (!empty($data['chesun_3'])) {
                $type = 2;
                // $date['chesun_3']=$data['chesun_3'];
                $data_s   = Db::name("sanche")->where("id", $id)->where("status", "1")->find();
                $data_arr = array();
                if ($data['chesun_3'] == 3) {
                    $msg                = "【{$data_s['car_num']}】三者车损核价审核通过";
                    $data_arr['status'] = 2;
                    $data_arr['tui']    = 1;
                    Db::name('lisuan')->where('bid', $bid)->where("sid", $id)->where('type',2)->delete();

                }
                if ($data['chesun_3'] == 2) {
                    $msg                = "【{$data_s['car_num']}】三者车核价损退回";
                    $data_arr['status'] = 0;
                    $data_arr['tui']    = 2;
                }
                $res = Db::name("sanche")->where("id", $id)->where("status", "1")->update($data_arr);
            } elseif (!empty($data['chesun_4'])) {
                $type = 3;
                // $date['chesun_3']=$data['chesun_3'];
                $data_s   = Db::name("scwusun")->where("id", $id)->where("status", "1")->find();
                $data_arr = array();
                if ($data['chesun_4'] == 3) {
                    $msg                = "【{$data_s['name']}】三者财物损失核价审核通过";
                    $data_arr['status'] = 2;
                    $data_arr['tui']    = 1;
                    Db::name('lisuan')->where('bid', $bid)->where("sid", $id)->where('type',3)->delete();
                }
                if ($data['chesun_4'] == 2) {
                    $msg                = "【{$data_s['name']}】三者财物损失核价退回";
                    $data_arr['status'] = 0;
                    $data_arr['tui']    = 2;
                }
                $res = Db::name("scwusun")->where("id", $id)->where("status", "1")->update($data_arr);
            } elseif (!empty($data['renshang_1'])) {
                $type = 4;
                // $date['renshang_1']=$data['renshang_1'];
                $data_s   = Db::name("benren")->where("id", $id)->where("status", "1")->find();
                $data_arr = array();
                if ($data['renshang_1'] == 3) {
                    $msg                = "【{$data_s['name']}】本车人伤核价审核通过";
                    $data_arr['status'] = 2;
                    $data_arr['tui']    = 1;
                    Db::name('lisuan')->where('bid', $bid)->where("sid", $id)->where('type',4)->delete();
                }
                if ($data['renshang_1'] == 2) {
                    $msg                = "【{$data_s['name']}】本车人伤核价退回";
                    $data_arr['status'] = 0;
                    $data_arr['tui']    = 2;
                }
//                dump($data_s);die;
                $res = Db::name("benren")->where("id", $id)->where("status", "1")->update($data_arr);
            } elseif (!empty($data['renshang_2'])) {
                $type = 5;
                // $date['renshang_2']=$data['renshang_2'];
                $data_s = Db::name("sanren")->where("id", $id)->where("status", "1")->find();
                if ($data['renshang_2'] == 3) {
                    $msg                = "【{$data_s['name']}】三者人伤核价审核通过";
                    $data_arr['status'] = 2;
                    $data_arr['tui']    = 1;
                    Db::name('lisuan')->where('bid', $bid)->where("sid", $id)->where('type',5)->delete();
                }
                if ($data['renshang_2'] == 2) {
                    $msg                = "【{$data_s['name']}】三者人伤核价退回";
                    $data_arr['status'] = 0;
                    $data_arr['tui']    = 2;
                }
                $res = Db::name("sanren")->where("id", $id)->where("status", "1")->update($data_arr);
            } else {
                exit();
            }

            if (!empty($res)) {
                //判断是否都通过了就到下一个
                $res_info = Db::name('baoan')->where('id', $bid)->find();
                /*
                if($res_info['chesun_1']=='3' && $res_info['chesun_2']=='3' &&$res_info['chesun_3']=='3' && $res_info['renshang_1']=='3' && $res_info['renshang_2']=='3'){
                */
                if ($res_info['chesun_1'] == '3' ||
                    $res_info['chesun_2'] == '3' ||
                    $res_info['chesun_3'] == '3' ||
                    $res_info['renshang_1'] == '3' ||
                    $res_info['renshang_2'] == '3'
                ) {

//                    if ($res_info['chesun_1'] == '3' && $res_info['chesun_2'] == '3' && $res_info['chesun_3'] == '3') {
//                        $date['chesun'] = 3;//车损通过
//                    }
//                    if ($res_info['renshang_1'] == '3' && $res_info['renshang_2'] == '3') {
//                        $date['renshang'] = 3;//人伤通过
//                    }
                    // $date['status'] = 1;
                    // $res = Db::name('baoan')->where('id',$id)->update($date);
                }
//                return json(["code" => 1, 'msg' => $msg . '操作成功']);
            }
            $this->add_baoyijian($bid, $msg . $tuihui, $type);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => $msg]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }

    }

    /**
     * 添加补偿单意见
     * 合并成一个方法
     */
    private function add_baoyijian($bid, $tuihui, $type = 0)
    {
        $yijian = [
            'bid'     => $bid,
            'type'    => $type,
            'name'    => session::get('admin')['username'],
            'tuihui'  => $tuihui,
            'time'    => time(),
            'user_id' => session::get('admin')['id']
        ];
        Db::name('byijian')->insert($yijian);
    }

    //核定配件保存----------------------------------------------


    public function hd_benches()
    {
        $data = request()->param();
        $add  = count($data['id']);
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['price_he'] = $data['price'][$i];
                $date['num_he']   = $data['num'][$i];
                $date['hejia']    = $data['money'][$i];
                $date['beizhu']   = $data['beizhu'][$i];
                $res              = Db::name("peijian")->where('id', $data['id'][$i])->update($date);
            }

            $data_arr                     = array();
            $data_arr['hd_benche_heji']   = $this->request->post("hd_a_heji", 0, "floatval");
            $data_arr['hd_benche_canzhi'] = $this->request->post("hd_a_canzhi", 0, "floatval");
            $data_arr['hd_benche_zongji'] = $this->request->post("hd_a_zongji", 0, "floatval");
            Db::name("baoan")->where("id", $data['bid'])->update($data_arr);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    public function hd_bengongs()
    {
        $data   = request()->param();
        $add    = count($data['id']);
        $result = [];
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['price_he'] = $data['price'][$i];
                $date['num_he']   = $data['num'][$i];
                $date['hejia']    = $data['money'][$i];
                $date['beizhu']   = $data['beizhu'][$i];
                $res              = Db::name("bengong")->where('id', $data['id'][$i])->update($date);
            }

            $data_arr                      = array();
            $data_arr['hd_bengong_shijiu'] = $this->request->post("hd_b_shijiu", 0, "floatval");
            $data_arr['hd_bengong_zongji'] = $this->request->post("hd_b_zongji", 0, "floatval");
            Db::name("baoan")->where("id", $data['bid'])->update($data_arr);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }

//        if ($res !==false)  $this->success('保存成功','',$result);
//        $this->error('保存失败');
    }

    public function hd_sanpeis()
    {
        $data = request()->param();
        $add  = count($data['id']);
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['price_he'] = $data['price'][$i];
                $date['num_he']   = $data['num'][$i];
                $date['hejia']    = $data['money'][$i];
                $res              = Db::name("sanpei")->where('id', $data['id'][$i])->update($date);
            }

            $data_arr                = array();
            $data_arr['hd_p_heji']   = $this->request->post("hd_c_heji", 0, "floatval");
            $data_arr['hd_canzhi']   = $this->request->post("hd_c_canzhi", 0, "floatval");
            $data_arr['hd_p_zongji'] = $this->request->post("hd_c_zongji", 0, "floatval");
            Db::name("sanche")->where("id", $data['sanche_id'])->update($data_arr);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    public function hd_sangongs()
    {
        $data = request()->param();
        $add  = count($data['id']);
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['price_he'] = $data['price'][$i];
                $date['num_he']   = $data['num'][$i];
                $date['hejia']    = $data['money'][$i];
                $res              = Db::name("sangong")->where('id', $data['id'][$i])->update($date);
            }

            $data_arr                = array();
            $data_arr['hd_g_shijiu'] = $this->request->post("hd_d_shijiu", 0, "floatval");
            $data_arr['hd_g_zongji'] = $this->request->post("hd_d_zongji", 0, "floatval");
            Db::name("sanche")->where("id", $data['sanche_id'])->update($data_arr);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }

    }

    public function hd_sanwus()
    {
        $data = request()->param();
        $add  = count($data['id']);
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['price_he'] = $data['price'][$i];
                $date['num_he']   = $data['num'][$i];
                $date['hejia']    = $data['money'][$i];
                $res              = Db::name("sancai")->where('id', $data['id'][$i])->update($date);
            }

            $data_arr                = array();
            $data_arr['hd_c_canzhi'] = $this->request->post("hd_e_canzhi", 0, "floatval");
            $data_arr['hd_c_heji']   = $this->request->post("hd_e_heji", 0, "floatval");
            $data_arr['hd_c_zongji'] = $this->request->post("hd_e_zongji", 0, "floatval");
            Db::name("scwusun")->where("id", $data['bid'])->update($data_arr);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    public function hd_benrens()
    {
        $data = request()->param();
        $add  = count($data['id']);
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['hejia'] = $data['hejia'][$i];
                $res           = Db::name("renshang")->where('id', $data['id'][$i])->update($date);
            }

            $data_arr          = array();
            $data_arr['hejia'] = $this->request->post("sum", 0, "floatval");
            Db::name("benren")->where("id", $data['bid'])->update($data_arr);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    public function hd_sanrens()
    {
        $data = request()->param();
        $add  = count($data['id']);
        // 启动事务
        Db::startTrans();
        try {
            for ($i = 0; $i < $add; $i++) {
                $date['hd_price'] = $data['money'][$i];
                $date['hd_num']   = $data['num'][$i];
                $date['hejia']    = $data['hejia'][$i];
                $res              = Db::name("renshang")->where('id', $data['id'][$i])->update($date);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    /*
    * 三者车人伤保存
    */
    public function sanzheren_bc()
    {
        $data = request()->param();
        $id   = $data['bid'];
        unset($data['bid']);
        // 启动事务
        Db::startTrans();
        try {
            $res = db('baoan')->where('id', $id)->update($data);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    //核定配件保存----------------------------------------------


    /*
     *三者车浏览
     */
    public function liulan()
    {
        $id      = request()->param()['id'];
        $sanche  = Db::name('sanche')->where('id', $id)->find();
        $sanpei  = Db::name('sanpei')->where('sid', $id)->select();
        $sanpei1 = 1;
        foreach ($sanpei as $k => $v) {
            if ($v['num_he'] <> 0) {
                $sanpei1 = 2;
            }
        }
        $sangong       = Db::name('sangong')->where('sid', $id)->select();
        $sancai        = Db::name('sancai')->where('sid', $id)->select();
        $he_price      = 0;
        $he_price_gong = 0;
        foreach ($sanpei as $k => $v) {
            $he_price = bcadd($he_price, $v['price_he'], 2);
        }


        $sangong1 = 1;
        foreach ($sangong as $k => $v) {
            if ($v['num_he'] <> 0) {
                $sangong1 = 2;
            }
        }
        foreach ($sangong as $k1 => $v1) {
            $he_price_gong = bcadd($he_price_gong, $v1['price_he'], 2);
        }
        $sanche['he_price_pei']  = $he_price;
        $sanche['he_price_gong'] = $he_price_gong;

        $lisuan   = Db::name('lisuan')->where('bid', $sanche['bid'])->where("sid", $sanche['id'])->find();
        $shoukuan = Db::name('shoukuan')->where('bid', $sanche['bid'])->where('sid', $sanche['id'])->select();
        $qita     = Db::name('qita')->where('bid', $sanche['bid'])->where('sid', $sanche['id'])->select();
        return json(['status' => true, 'msg' => '成功', 'data' => ['sanche' => $sanche, 'sanpei' => $sanpei, 'sangong' => $sangong, 'sancai' => $sancai, 'sanpei1' => $sanpei1, 'sangong1' => $sangong1, 'lisuan' => $lisuan, 'shoukuan' => $shoukuan, 'qita' => $qita]]);
    }

    /*
     *三者财浏览修改
     */
    public function liulan_cai()
    {
        $id       = request()->param()['id'];
        $scwusun  = Db::name('scwusun')->where('id', $id)->find();
        $sancai   = Db::name('sancai')->where('sid', $scwusun['id'])->select();
        $lisuan   = Db::name('lisuan')->where('bid', $scwusun['bid'])->where("sid", $scwusun['id'])->find();
        $shoukuan = Db::name('shoukuan')->where('bid', $scwusun['bid'])->where('sid', $scwusun['id'])->select();
        $qita     = Db::name('qita')->where('bid', $scwusun['bid'])->where('sid', $scwusun['id'])->select();
        return json(['status' => true, 'msg' => '成功', 'data' => ['scwusun' => $scwusun, "sancai" => $sancai, 'lisuan' => $lisuan, 'shoukuan' => $shoukuan, 'qita' => $qita]]);
    }

    /*
   * 本车人伤浏览
   */
    public function benrens()
    {
        $id       = request()->param()['id'];
        $renshang = Db::name('renshang')->where('bid', $id)->select();
        $benren   = Db::name('benren')->where('id', $id)->find();
        $lisuan   = Db::name('lisuan')->where('bid', $benren['bid'])->where("sid", $benren['id'])->find();

        $shoukuan = Db::name('shoukuan')->where('bid', $benren['bid'])->where('sid', $benren['id'])->select();
        $qita     = Db::name('qita')->where('bid', $benren['bid'])->where('sid', $benren['id'])->select();
        return json(['status' => true, 'msg' => '成功', 'data' => ['renshang' => $renshang, 'benren' => $benren, 'lisuan' => $lisuan, 'shoukuan' => $shoukuan, 'qita' => $qita]]);
    }

    /*
    *本车人伤保存
    */
    public function renshangs()
    {
        $data                 = request()->param();
        $bid                  = $data['id'];
        $id                   = $data['bid'];
        $date['bingqing']     = $data['bingqing'];
        $date['zhuyuan']      = $data['zhuyuan'];
        $date['zhuyuan_date'] = $data['zhuyuan_date'];
        $date['canji']        = $data['canji'];
        $date['money']        = $data['money'];
        $date['susong_fee']   = $data['benren_susong'];
        $date['jianding_fee'] = $data['benren_jianding'];
        $date['gonggu_fee']   = $data['benren_gonggu'];
        $date['zhusu_fee']    = $data['benren_zhusu'];
        $date['luqiao_fee']   = $data['benren_luqiao'];
        $date['ranyou_fee']   = $data['benren_ranyou'];
        $date['qita_fee']     = $data['benren_qita'];
        // 启动事务
        Db::startTrans();
        try {
//            if ($data['tan_kuai_shen_4']) {
//
//
//                $ress = Db::name('lisuan')->where('bid', $data['id'])->where("sid", $data['bid'])->find();
//                // dump($ress);die;
//                if ($ress) {
//                    $res = Db::name('lisuan')->where('bid', $data['id'])->where("sid", $data['bid'])->update(['kuai' => $data['tan_kuai_shen_4']]);
//                } else {
//                    $res = Db::name('lisuan')->insert(['kuai' => $data['tan_kuai_shen_4'], 'sid' => $data['bid'], 'bid' => $data['id']]);
//                }
//            }
            $res  = Db::name('benren')->where('id', $id)->where("status", "0")->update($date);
            $ress = Db::name('benren')->where('bid', $bid)->select();
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功', 'res' => $ress]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }





    /**
     * 三这个详细
     */
    public function sanzheche($id){
        $this->assign('id', $id);
        return $this->fetch('bushen/hejia/peijian/sanzheche');
    }


}
